package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.constraints.NotEmpty;
import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

/**
 * @author lingkang
 * Created by 2024/1/26
 */
public class NotEmptyHandle extends ValidHandle {
    private final String errorStr;
    private final NotEmpty notEmpty;

    public NotEmptyHandle(ValidVal validVal, NotEmpty notEmpty) {
        super(validVal, notEmpty);
        this.notEmpty = notEmpty;

        if (FinalValidatorUtils.isNotEmpty(notEmpty.message())) {
            errorStr = notEmpty.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("NotEmpty").replace("{attrName}", validVal.getTag());
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("NotEmpty").replace("{attrName}", validVal.getName());
        }
    }

    @Override
    public void valid(Object target) {
        Object o = validVal.getValGet().get(target);
        if (o == null || o.toString().isEmpty()) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    @Override
    public Class<?>[] getGroups() {
        return notEmpty.groups();
    }
}
